package com.docmgmt.mvp.controller;

import com.docmgmt.mvp.dto.AddKbMemberRequest;
import com.docmgmt.mvp.dto.KbMemberVO;
import com.docmgmt.mvp.dto.Result;
import com.docmgmt.mvp.dto.UpdateKbMemberRequest;
import com.docmgmt.mvp.exception.UnauthorizedException;
import com.docmgmt.mvp.service.impl.MemberServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 知识库成员管理控制器（KB-008）
 * <p>
 * 功能：
 * - 添加成员（用户/部门）
 * - 移除成员
 * - 更新成员权限
 * - 查询知识库成员列表
 * - 查询用户在知识库的权限
 * <p>
 * 权限要求：
 * - 仅知识库owner可管理成员（添加/移除/更新权限）
 * - 所有有权限的用户可查看成员列表
 *
 * @author Dora
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/kb")
@RequiredArgsConstructor
@Tag(name = "知识库成员管理", description = "KB-008: 知识库成员管理API（支持用户和部门授权）")
public class MemberController {

    private final MemberServiceImpl memberService;

    /**
     * 添加知识库成员
     *
     * POST /api/v1/kb/{kbId}/members
     */
    @PostMapping("/{kbId}/members")
    @Operation(summary = "添加知识库成员", description = "添加用户或部门到知识库，仅owner可操作")
    public Result<KbMemberVO> addMember(
            @Parameter(description = "知识库ID") @PathVariable Long kbId,
            @Valid @RequestBody AddKbMemberRequest request) {

        Long operatorId = getCurrentUserId();

        log.info("POST /api/v1/kb/{}/members - operatorId={}, request={}",
                kbId, operatorId, request);

        KbMemberVO member = memberService.addMember(kbId, request, operatorId);

        return Result.success("成员添加成功", member);
    }

    /**
     * 移除知识库成员
     *
     * DELETE /api/v1/kb/{kbId}/members/{memberType}/{memberId}
     */
    @DeleteMapping("/{kbId}/members/{memberType}/{memberId}")
    @Operation(summary = "移除知识库成员", description = "移除用户或部门的知识库权限，仅owner可操作")
    public Result<Void> removeMember(
            @Parameter(description = "知识库ID") @PathVariable Long kbId,
            @Parameter(description = "成员类型：user/dept") @PathVariable String memberType,
            @Parameter(description = "成员ID") @PathVariable Long memberId) {

        Long operatorId = getCurrentUserId();

        log.info("DELETE /api/v1/kb/{}/members/{}/{} - operatorId={}",
                kbId, memberType, memberId, operatorId);

        memberService.removeMember(kbId, memberType, memberId, operatorId);

        return Result.success("成员移除成功");
    }

    /**
     * 更新成员权限
     *
     * PUT /api/v1/kb/{kbId}/members/{memberType}/{memberId}
     */
    @PutMapping("/{kbId}/members/{memberType}/{memberId}")
    @Operation(summary = "更新成员权限", description = "修改用户或部门的权限级别，仅owner可操作")
    public Result<KbMemberVO> updateMemberPermission(
            @Parameter(description = "知识库ID") @PathVariable Long kbId,
            @Parameter(description = "成员类型：user/dept") @PathVariable String memberType,
            @Parameter(description = "成员ID") @PathVariable Long memberId,
            @Valid @RequestBody UpdateKbMemberRequest request) {

        Long operatorId = getCurrentUserId();

        log.info("PUT /api/v1/kb/{}/members/{}/{} - operatorId={}, request={}",
                kbId, memberType, memberId, operatorId, request);

        KbMemberVO member = memberService.updateMemberPermission(
                kbId, memberType, memberId, request, operatorId);

        return Result.success("权限更新成功", member);
    }

    /**
     * 查询知识库所有成员
     *
     * GET /api/v1/kb/{kbId}/members
     */
    @GetMapping("/{kbId}/members")
    @Operation(summary = "查询知识库成员列表", description = "查询知识库所有成员及其权限，需要有知识库访问权限")
    public Result<List<KbMemberVO>> listMembers(
            @Parameter(description = "知识库ID") @PathVariable Long kbId) {

        Long userId = getCurrentUserId();

        log.info("GET /api/v1/kb/{}/members - userId={}", kbId, userId);

        List<KbMemberVO> members = memberService.listMembers(kbId, userId);

        return Result.success("查询成功", members);
    }

    /**
     * 查询用户在知识库的权限
     *
     * GET /api/v1/kb/{kbId}/permission
     */
    @GetMapping("/{kbId}/permission")
    @Operation(summary = "查询用户权限", description = "查询当前用户在知识库中的权限级别")
    public Result<String> getUserPermission(
            @Parameter(description = "知识库ID") @PathVariable Long kbId) {

        Long userId = getCurrentUserId();

        log.info("GET /api/v1/kb/{}/permission - userId={}", kbId, userId);

        String permission = memberService.getUserPermissionInKb(kbId, userId);

        if (permission == null) {
            return Result.success("无权限", "no_access");
        }

        return Result.success("查询成功", permission);
    }

    /**
     * 从Spring Security上下文获取当前用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new UnauthorizedException("未登录或认证已过期");
        }

        Object principal = authentication.getPrincipal();
        if (principal instanceof Long) {
            return (Long) principal;
        }

        throw new UnauthorizedException("无效的认证信息");
    }
}
